<template>
  <transition name="slide">
    <music-list :rank="rank" :title="title" :bg-image="bgImage" :songs="songs" />
  </transition>
</template>

<script>
import MusicList from '../music-list/MusicList'
import { mapGetters } from 'vuex'
import { getRankDetailList, getSongsUrls } from '../../api/index'
import { createSong } from '../../assets/js/song'

export default {
  name: 'TopList',
  data() {
    return {
      songs: [],
      rank: true
    }
  },
  computed: {
    title() {
      return this.topList.name
    },
    bgImage() {
      if (this.songs.length) {
        return this.songs[0].image
      }
      // return this.topList.coverImgUrl // 这图片太丑
      return ''
    },
    ...mapGetters([
      'topList'
    ])
  },
  created() {
    this._getRankDetailList()
  },
  methods: {
    _getRankDetailList() {
      if (!this.topList.id) {
        // 为了防止在本页面进行刷新拿不到id, 我们直接返回rank界面
        this.$router.push('/rank')
        return
      }
      getRankDetailList({ idx: this.topList.ToplistType.charCodeAt() - 65 }).then(res => {
        if (res.statusText === 'OK') {
          console.log(res)
          this.songs = this._normalizeSongs(res.data.playlist.tracks)
        }
        // 将歌曲列表的各个id单独放到一个数组, 去另外取歌曲url
        const songsID = []
        this.songs.forEach(song => {
          songsID.push(song.id)
        })
        return songsID
      }).then(songsID => {
        return getSongsUrls({ id: songsID.join(',') })
      }).then(songsUrl => {
        for (let i = 0; i < songsUrl.data.data.length; i++) {
          this.songs[i].url = songsUrl.data.data[i].url
        }
      }).catch(err => {
        console.log(err)
      })
    },
    _normalizeSongs(list) {
      const ret = []
      list.forEach(item => {
        if (item.id) {
          ret.push(createSong(item))
        }
      })
      return ret
    }
  },
  components: {
    MusicList
  }
}
</script>

<style lang="scss" scoped>
.slide-enter-active, .slide-leave-active{
  transition: all 0.3s ease;
}
.slide-enter, .slide-leave-to{
  transform: translate3d(100%, 0, 0);
}
</style>